<template>
  <div
      class="login-container min-h-screen flex items-center justify-center bg-gray-50 p-4 relative overflow-hidden"
  >
    <!-- 背景装饰元素 -->
    <div
        class="absolute top-0 right-0 w-1/2 h-full bg-gradient-to-b from-blue-50 to-white -skew-x-12 transform origin-top-right opacity-20 pointer-events-none"
    ></div>
    <div
        class="absolute bottom-0 left-0 w-1/3 h-1/2 bg-blue-50 rounded-full -translate-y-1/2 opacity-10 pointer-events-none"
    ></div>

    <!-- 主容器 -->
    <div class="relative w-full max-w-md bg-white rounded-2xl shadow-xl overflow-hidden z-10">
      <!-- 顶部装饰 -->
      <div class="h-1 bg-gradient-to-r from-blue-500 to-indigo-500"></div>

      <!-- 头部区域 -->
      <div class="p-6 border-b border-gray-100">
        <div class="flex items-center justify-center mb-4">
          <!-- <div class="w-12 h-12 rounded-lg bg-blue-500 flex items-center justify-center text-white">
            <i class="fa fa-key text-xl"></i>
          </div> -->
          <h1 class="text-xl font-bold text-gray-900">AetherCore</h1>
        </div>
        <p class="text-gray-500 text-sm text-center">登录</p>
      </div>

      <!-- 表单区域 -->
      <div class="p-6 space-y-5">
        <!-- 账号输入 -->
        <div class="space-y-1">
          <label for="email" class="block text-sm font-medium text-gray-700">账号</label>
          <div class="relative">
            <span class="absolute inset-y-0 left-0 flex items-center pl-3 text-gray-400">
              <i class="fa fa-envelope"></i>
            </span>
            <input
                v-model="data.account"
                type="email"
                id="email"
                class="w-full pl-10 pr-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500/50 focus:border-blue-500 transition-all duration-300 outline-none"
                placeholder="your@password"
                required
            />
          </div>
        </div>

        <!-- 密码输入 -->
        <div class="space-y-1">
          <div class="flex justify-between items-center">
            <label for="password" class="block text-sm font-medium text-gray-700">密码</label>
            <a
                href="#"
                class="text-sm text-blue-500 hover:text-blue-700 transition-colors duration-200"
            >忘记密码?</a
            >
          </div>
          <div class="relative">
            <span class="absolute inset-y-0 left-0 flex items-center pl-3 text-gray-400">
              <i class="fa fa-lock"></i>
            </span>
            <input
                v-model="data.password"
                @keyup.enter="handleLogin"
                :type="showPassword ? 'text' : 'password'"
                id="password"
                class="w-full pl-10 pr-10 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500/50 focus:border-blue-500 transition-all duration-300 outline-none"
                placeholder="••••••••"
                required
            />
            <button
                type="button"
                @click="togglePasswordVisibility"
                class="absolute inset-y-0 right-0 flex items-center pr-3 text-gray-400 hover:text-gray-600 transition-colors duration-200"
            >
              <i :class="showPassword ? 'fa fa-eye-slash' : 'fa fa-eye'"></i>
            </button>
          </div>
        </div>

        <!-- 记住我 -->
        <div class="flex items-center">
          <input
              id="remember"
              type="checkbox"
              class="h-4 w-4 text-blue-500 focus:ring-blue-500 border-gray-300 rounded"
              v-model="rememberMe"
          />
          <label for="remember" class="ml-2 block text-sm text-gray-700">记住我 (30天)</label>
        </div>

        <!-- 登录按钮 -->
        <button
            type="button"
            @click="handleLogin"
            class="w-full bg-gradient-to-r from-blue-500 to-indigo-500 text-white py-3 px-4 rounded-lg font-medium hover:from-blue-600 hover:to-indigo-600 focus:ring-4 focus:ring-blue-300/30 focus:outline-none transition-all duration-300 transform hover:-translate-y-1 flex items-center justify-center"
        >
          <span>登录</span>
          <i class="fa fa-arrow-right ml-2 text-sm"></i>
        </button>
      </div>

      <!-- 底部区域 -->
      <div class="p-6 border-t border-gray-100 bg-gray-50">
        <div class="text-center text-sm text-gray-500 mb-4">
          还没有账户?
          <a
              href="#"
              class="font-medium text-blue-500 hover:text-blue-700 transition-colors duration-200"
          >立即注册</a
          >
        </div>
        <div class="flex justify-center space-x-4">
          <a href="#" class="text-gray-400 hover:text-blue-500 transition-colors duration-200">
            <i class="fa fa-github text-xl"></i>
          </a>
          <a href="#" class="text-gray-400 hover:text-blue-500 transition-colors duration-200">
            <i class="fa fa-twitter text-xl"></i>
          </a>
          <a href="#" class="text-gray-400 hover:text-blue-500 transition-colors duration-200">
            <i class="fa fa-discord text-xl"></i>
          </a>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, inject, onMounted } from 'vue'
import sessionUtil from '@/utils/session'
// import router from '@/router'
import { useRouter } from 'vue-router'
const router = useRouter()
const api = inject('api')
const ifMobile = inject('ifMobile')
const memberApi = api.getApi('FaSysMember')

// 表单数据
const data = ref({
  account: '',
  password: ''
})

// 记住密码状态
const rememberMe = ref(false)

// 密码显示控制
const showPassword = ref(false)

// 切换密码可见性
const togglePasswordVisibility = () => {
  showPassword.value = !showPassword.value
}

// 处理登录
const handleLogin = () => {
  // 登录
  login()
}

// 登录函数优化版本
async function login() {
  const loginBtn = document.querySelector('button[type="button"]')
  // 1. 定义加载状态处理函数
  const handleLoading = (isLoading) => {
    if (!loginBtn.value) return // 防御性编程

    loginBtn.value.disabled = isLoading
    loginBtn.value.innerHTML = isLoading
        ? '<i class="fa fa-spinner fa-spin mr-2"></i> 登录中...'
        : '<span>登录</span><i class="fa fa-arrow-right ml-2 text-sm"></i>'
  }

  // 2. 定义登录成功处理函数
  const handleLoginSuccess = (res) => {
    // 存储登录信息
    sessionUtil.setItem('member', JSON.stringify(res.data.member))
    sessionUtil.setItem('menuTree', JSON.stringify(res.data.menuTree))
    sessionUtil.setItem('token', res.data.token)

    // 处理记住密码
    if (rememberMe.value) {
      localStorage.setItem(
          'userData',
          JSON.stringify({
            account: data.value.account,
            password: data.value.password,
            remember: true
          })
      )
    } else {
      localStorage.removeItem('userData')
    }
    // 预加载数据
    api
        .getApi('FaSysSettings', null)
        .getByKeyName('GRID_FUNCTION')
        .then((res) => {
          sessionUtil.setItem('functionRole', res.data.value)
        })
    // 加载路由
    loadRouter(res.data.menuTree)
    // 页面跳转
    if (ifMobile) {
      router.push('/mbHome')
    } else {
      router.push('/home')
    }
  }
  // 获取全部组件
  let modules = import.meta.glob('@/views/template/**/IndexView.vue')
  const addRouters = []
  // 加载路由
  function loadRouter(menuTree) {
    for (const key in menuTree) {
      const item = menuTree[key]
      if (item.children.length > 0) {
        for (const key in item.children) {
          const routerItem = item.children[key]
          addRoute(routerItem)
        }
      } else {
        addRoute(item)
      }
    }
    // 缓存动态路由
    sessionUtil.setItem('router', JSON.stringify(addRouters))
  }

  function addRoute(routerItem) {
    let routerJson = JSON.parse(routerItem.router)
    // 判断是否设置路由
    if (routerJson.meta?.componentPath) {
      const addRoute = {
        ...routerJson,
        component: modules[routerJson.meta.componentPath]
      }
      addRoute.meta.grids = JSON.parse(routerItem.grids)
      addRoute.meta.functionRole = routerItem.functionRole
      addRouters.push(addRoute)
      router.addRoute('homeIndex', addRoute)
    }
    // 添加其他路由
    let otherRouterJson = JSON.parse(routerItem.otherRouterJson)
    // 判断是否设置其他路由
    if (otherRouterJson && otherRouterJson.length > 0) {
      for (const key in otherRouterJson) {
        const otherRouteItem = otherRouterJson[key]
        // 存在其他路由
        const addotherRoute = {
          ...otherRouteItem
        }
        if (otherRouteItem?.meta?.componentPath) {
          addotherRoute.component = modules[otherRouteItem.meta.componentPath]
        }
        addRouters.push(addotherRoute)
        router.addRoute('homeIndex', addotherRoute)
      }
    }
  }

  // 3. 定义错误处理函数
  const handleError = (err) => {
    console.error('登录失败:', err)
    // 这里可以添加错误提示逻辑
    // 例如: ElMessage.error('登录失败，请检查账号密码');
  }

  // 4. 主逻辑流程
  try {
    // 显示加载状态
    handleLoading(true)

    // 调用登录API
    const res = await memberApi.login(data.value)

    // 处理登录结果
    if (res.code === 200) {
      handleLoginSuccess(res)
    } else {
      handleError(new Error(res.message || '登录失败'))
    }
  } catch (err) {
    handleError(err)
  } finally {
    // 确保无论成功失败都恢复按钮状态
    handleLoading(false)
  }
}

// 组件挂载时检查是否有记住的登录信息
onMounted(() => {
  const userData = localStorage.getItem('userData')
  if (userData) {
    const parsedData = JSON.parse(userData)
    data.value = parsedData
    rememberMe.value = true
  }
})
</script>

<style scoped>
/* 全局样式 */
body {
  font-family:
      -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans',
      'Helvetica Neue', sans-serif;
}

/* 自定义动画 */
@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

/* 应用动画 */
.login-container > div {
  animation: fadeIn 0.5s ease-out forwards;
}
</style>
